package com.tianbao54.concurrent.threadpool;

import java.lang.reflect.Field;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class RejectedHandlerTest {

    static void log (String msg) {
        System.out.println(System.currentTimeMillis() + " -> " + msg);
    }

    static int getThreadPoolRunState(ThreadPoolExecutor pool) throws Exception {
        Field f = ThreadPoolExecutor.class.getDeclaredField("runState");
        f.setAccessible(true);
        int v = f.getInt(pool);
        return v;
    }

    public static void main(String[] args) throws Exception {

        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(1,1,0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1));
        poolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        for (int i = 0 ; i < 10 ; i ++) {
            final int index = i;
            poolExecutor.submit(() -> {
                log("run task:" + index + " -> " + Thread.currentThread().getName());
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log("run over:" + index + " -> " + Thread.currentThread().getName());
            });
        }

        log("before sleep");
        Thread.sleep(4000L);
        log("before shutdown()");
        poolExecutor.shutdown();
        log("after shutdown(),pool.isTerminated=" + poolExecutor.isTerminated());
        poolExecutor.awaitTermination(1000L, TimeUnit.SECONDS);
        log("now,pool.isTerminated=" + poolExecutor.isTerminated() + ", state="
                + getThreadPoolRunState(poolExecutor));
    }
}
